<template>
  <div class="question-container">
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <el-row>
        <el-col :span="16">
          <el-form label-width="80px" inline size="small">
            <el-form-item label="学科名称">
              <el-input v-model="pageParams.subjectName"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="pageParams.subjectName = ''">清除</el-button>
              <el-button type="primary" @click="loadSubjectsList"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8" style="text-align: right">
          <el-button
            type="success"
            icon="el-icon-edit"
            size="small"
            @click="hAdd"
            >新增学科</el-button
          >
        </el-col>
      </el-row>
      <!-- 信息提示组件 -->
      <el-row style="margin-bottom: 15px">
        <el-alert
          :title="'数据一共 ' + total + ' 条'"
          type="info"
          show-icon
          :closable="false"
        ></el-alert>
      </el-row>
      <!-- 表格组件 -->
      <el-row>
        <el-table :data="subjectsList" style="width: 100%" fit>
          <el-table-column type="index" label="序号"> </el-table-column>
          <el-table-column prop="subjectName" label="学科名称">
          </el-table-column>
          <el-table-column prop="username" label="创建者"> </el-table-column>
          <el-table-column prop="addDate" label="创建日期"> </el-table-column>
          <el-table-column prop="isFrontDisplay" label="前台是否显示">
            <template v-slot="scope">
              {{ scope.row.isFrontDisplay ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column prop="twoLevelDirectory" label="二级目录">
          </el-table-column>
          <el-table-column prop="tags" label="标签"> </el-table-column>
          <el-table-column prop="totals" label="题目数量"> </el-table-column>
          <el-table-column label="操作" width="240px">
            <template v-slot="scope">
              <el-button
                type="text"
                @click="
                  $router.push(
                    '/subjects/directorys?id=' +
                      scope.row.id +
                      '&name=' +
                      scope.row.subjectName
                  )
                "
                >学科分类</el-button
              >
              <el-button
                type="text"
                @click="
                  $router.push(
                    '/subjects/tags?id=' +
                      scope.row.id +
                      '&name=' +
                      scope.row.subjectName
                  )
                "
                >学科标签</el-button
              >
              <el-button type="text" @click="hEdit(scope.row.id)"
                >修改</el-button
              >
              <el-button
                type="text"
                @click="hDel(scope.row.id)"
                :disabled="
                  scope.row.twoLevelDirectory !== 0 || scope.row.tags !== 0
                "
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <!-- 分页组件 -->
      <el-row style="text-align: right">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="pageParams.page"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageParams.pagesize"
          layout="prev, pager, next, sizes, jumper"
          :total="total"
        >
        </el-pagination
      ></el-row>
    </el-card>

    <!-- 新增/编辑学科弹框 -->
    <el-dialog
      :visible.sync="showDialog"
      :title="isEdit ? '编辑学科' : '新增学科'"
      width="400px"
      @close="hClose"
    >
      <el-form
        label-width="80px"
        size="small"
        :rules="formRules"
        :model="formData"
        ref="formRef"
      >
        <el-form-item label="学科名称" prop="subjectName">
          <el-input
            v-model="formData.subjectName"
            placeholder="请输入学科名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            v-model="formData.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: right">
        <el-button @click="hCancel">取 消</el-button>
        <el-button type="primary" @click="hSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, add, detail, update, remove } from "@/api/hmmm/subjects";

export default {
  data() {
    const validateName = (rule, value, callback) => {
      if (this.simpleList.includes(value)) {
        callback(new Error(`学科名称 ${value} 已被占用`));
      } else {
        callback();
      }
    };
    return {
      pageParams: {
        page: 1,
        pagesize: 5,
        subjectName: "",
      },
      total: 0,
      subjectsList: [],
      simpleList: [],
      showDialog: false,
      formData: {
        subjectName: "",
        isFrontDisplay: false,
      },
      formRules: {
        subjectName: [
          { required: true, message: "学科名称不能为空", trigger: "blur" },
          { validator: validateName, trigger: "blur" },
        ],
      },
      isEdit: false,
      curId: "",
    };
  },
  created() {
    this.loadSubjectsList();
  },
  methods: {
    async loadSubjectsList() {
      const res = await list(this.pageParams);
      console.log(res);
      this.subjectsList = [...res.data.items];
      const resAll = await list({ page: 1, pagesize: 10000 });
      this.simpleList = resAll.data.items.map((item) => item.subjectName);
      this.total = res.data.counts;
    },
    handleSizeChange(curSize) {
      this.pageParams.pagesize = curSize;
      this.loadSubjectsList();
    },
    handleCurrentChange(curPage) {
      this.pageParams.page = curPage;
      this.loadSubjectsList();
    },
    hAdd() {
      this.showDialog = true;
      this.isEdit = false;
    },
    async hEdit(id) {
      this.showDialog = true;
      const res = await detail(id);
      console.log(res);
      this.formData = {
        subjectName: res.data.subjectName,
        isFrontDisplay: res.data.isFrontDisplay ? true : false,
        id: res.data.id,
      };
      this.isEdit = true;
      this.curId = id;
    },
    hSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd();
        }
      });
    },
    async doAdd() {
      try {
        const res = await add(this.formData);
        console.log(res);
        this.$message.success("新增学科成功");
        this.showDialog = false;
        this.loadSubjectsList();
      } catch (err) {
        this.$message.error(err.message);
      }
    },
    async doEdit() {
      try {
        const res = await update(this.formData);
        console.log(res);
        this.$message.success("修改学科成功");
        this.showDialog = false;
        this.loadSubjectsList();
      } catch (err) {
        this.$message.error(err.message);
      }
    },
    hCancel() {
      this.showDialog = false;
    },
    hClose() {
      this.$refs.formRef.resetFields();
      this.formData = {
        subjectName: "",
        isFrontDisplay: false,
      };
    },
    hDel(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.doDel(id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async doDel(id) {
      try {
        const res = await remove(id);
        console.log(res);
        this.$message.success("删除成功");
        if (this.total % this.pageParams.pagesize === 1) {
          this.pageParams.page--;
          this.pageParams.page = Math.max(1, this.pageParams.page);
        }
        this.loadSubjectsList();
      } catch (err) {
        this.$message.error(err.message);
      }
    },
  },
};
</script>

<style scoped lang='scss'>
</style>
